//
//  INSViewController.m
//  Berlin Insomniac
//
//  Created by Salánki, Benjámin on 06/03/14.
//  Copyright (c) 2014 Berlin Insomniac. All rights reserved.
//

#import "INSViewController.h"
#import "INSSearchBar.h"

#import "ViewController.h"

#import "ConnectModel.h"

#import "NotesViewController.h"
#import "DestinationsViewController.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)


@interface INSViewController () <INSSearchBarDelegate>

@property (nonatomic, strong) INSSearchBar *searchBarWithoutDelegate;
@property (nonatomic, strong) INSSearchBar *searchBarWithDelegate;

@end

@implementation INSViewController

#pragma mark - view life cycle
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SEARCHLOCATION" object:nil];
    [_searchArray release];
    [_location release];
    [_dataArray release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.location = _location;
        self.dataArray = _dataArray;
        self.tag = 52;
        self.searchArray = [NSMutableArray arrayWithObjects:@"不丹", @"新加坡", @"柬埔寨", @"日本", @"尼泊尔", @"美国", @"挪威", @"马来西亚", @"法国", nil];
        self.cityArray = [NSMutableArray arrayWithObjects:@"新疆", @"西藏", @"台湾", @"香港", @"澳门", @"云南", nil];
        // @"越南", @"缅甸", @"朝鲜", 
    }return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *img = [UIImage imageNamed:@"background vague.png"];
    UIImageView *imv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    imv.image = img;
    [self.view addSubview:imv];
	// self.view.backgroundColor = [UIColor colorWithRed:0.2 green:0.9 blue:0.2 alpha:1.000];
    
    // 放大镜起始位置:
	self.searchBarWithDelegate = [[INSSearchBar alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 + 5, 27, 44.0, 34.0)];
    // 控制 textField的大小
	self.searchBarWithDelegate.delegate = self;
	
	[self.view addSubview:self.searchBarWithDelegate];
    
    // 取消Button
    UIButton *cancle = [[[UIButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds) - 70, 27, 50, 34)] autorelease];
    cancle.backgroundColor = [UIColor whiteColor];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancle addTarget:self action:@selector(cancleAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancle];
    
    // 搜索
    UIButton *searchB = [[[UIButton alloc] initWithFrame:CGRectMake(20, 200, 30, 30)] autorelease];
    searchB.backgroundColor = [UIColor whiteColor];
    [searchB addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchB];
    
    // seg
    UISegmentedControl *seg = [[[UISegmentedControl alloc] initWithFrame:CGRectMake(20, 80, SCREEN_WIDTH - 40, 25)] autorelease];
    [seg setBackgroundColor:[UIColor colorWithRed:231/256 green:231/256 blue:231/256 alpha:1.0]];
    [seg insertSegmentWithTitle:@"国外" atIndex:0 animated:YES];
    [seg insertSegmentWithTitle:@"国内" atIndex:1 animated:YES];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:seg];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textAction:) name:@"SEARCHLOCATION" object:nil];
    
}
- (void)segAction:(UISegmentedControl *)seg
{
    NSInteger index = seg.selectedSegmentIndex;
    NSInteger num = 0;
    switch (index) {
        case 0:
            for (int i = 0; i < [_searchArray count] / 3; i++) {
                for (int j = 0; j < 3; j++) {
                     UIButton * country = [[[UIButton alloc] initWithFrame:CGRectMake(10 + j * (SCREEN_WIDTH - 20 - 10) / 3 + j * 5, 130 + i * 35, (SCREEN_WIDTH - 30) / 3, 25)] autorelease];
                    [country addTarget:self action:@selector(countryAction:) forControlEvents:UIControlEventTouchUpInside];
                    [country setTitle:[_searchArray objectAtIndex:num] forState:UIControlStateNormal];
                    [country setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    num++;
                    country.tag = _tag;
                    _tag++;
                    country.backgroundColor = [UIColor whiteColor];
                    [self.view addSubview:country];
                }
            }
            
            break;
        case 1:
            for (int i = 0; i < [_cityArray count] / 3; i++) {
                for (int j = 0; j < 3; j++) {
                    UIButton *country = [[[UIButton alloc] initWithFrame:CGRectMake(10 + j * (SCREEN_WIDTH - 20 - 10) / 3 + j * 5, 130 + i * 35, (SCREEN_WIDTH - 30) / 3, 25)] autorelease];
                    [country addTarget:self action:@selector(countryAction:) forControlEvents:UIControlEventTouchUpInside];
                    [country setTitle:[_cityArray objectAtIndex:num] forState:UIControlStateNormal];
                    [country setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    num++;
                    country.tag = _tag;
                    _tag++;
                    country.backgroundColor = [UIColor cyanColor];
                    [self.view addSubview:country];
                }
                
            }
            break;
        default:
            break;
    }
}
- (void)textAction:(NSNotification *)noti
{
    self.location = [noti.userInfo objectForKey:@"text"];
    NSLog(@"_location == %@", _location);
}

- (void)searchAction
{
    NSLog(@"search");
    // 通知
    NSString *str = [NSString stringWithFormat:@"%@", _location];
    
    NSMutableDictionary *DD = [NSMutableDictionary dictionaryWithObjectsAndKeys:str,@"name", nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(passAction:) name:@"PASSID" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PASSDATA" object:self userInfo:DD];
    
    

    [self connectParser];
}
- (void)passAction:(NSNotification *)noti
{
    _destination_id = [noti.userInfo objectForKey:@"ID"];
    NSLog(@"idid = %@", _destination_id);
}
- (void)countryAction:(UIButton *)sender
{
    NSLog(@"country!!");
    self.tagId = [NSString stringWithFormat:@"%ld", (long)sender.tag];
    NSLog(@"tag = %@", _tagId);
    NotesViewController *note = [[[NotesViewController alloc] init] autorelease];
    UINavigationController *na = [[[UINavigationController alloc] initWithRootViewController:note] autorelease];
     // self.navigationItem.title = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 25, 25)];
    back.backgroundColor = [UIColor cyanColor];
    back.imageView.image = [UIImage imageNamed:@"back.png"];
    [back addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [na.view addSubview:back];
    note.destination_id = self.tagId;
    [self presentViewController:na animated:YES completion:nil];
}

#pragma mark - search bar delegate

- (CGRect)destinationFrameForSearchBar:(INSSearchBar *)searchBar
{
    // 控制textField出来的位置
	return CGRectMake(20.0, 27, CGRectGetWidth(self.view.bounds) - 100.0, 34.0);
    
}

- (void)cancleAction
{
    NSLog(@"cancle");
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)backAction
{
    NSLog(@"back");
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 解析
- (void)connectParser
{

    NSString *pa = [NSString stringWithFormat:@"http://chanyouji.com/api/search/trips.json?q=%@&page=1", _location];
    NSString *path = [pa stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"@@@@@@-==%@", path);

    
    [ConnectModel connectModelWithUrl:path parmaters:nil finished:^(NSData *data) {

        self.dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (! _dataArray) {
            NSLog(@"无数据");
        }
        
        NotesViewController *note = [[NotesViewController alloc] init];
        note.destination_id = self.destination_id;
        [self presentViewController:note animated:YES completion:nil];

    }];
}
@end
